import { StateCreator, create } from 'zustand';
import { encrypt } from './rsaEncrypt.js'
import { NavigateFunction, useNavigate } from 'react-router-dom';
import { devtools, persist } from 'zustand/middleware';
import type { User } from '../../interfaces';
import { AuthService } from '../../services/auth.service';
import { login } from '@/api1/login/login'
import { message } from 'antd';
export interface AuthState {
  status: AuthStatus;
  token?: string;
  user?: User;
  loading?: boolean; // 添加 loading 字段
  loginUser: (email: string, password: string, navigate: NavigateFunction) => Promise<void>;
}

interface LoginResponse {
  code: number;
  data: {
    token: string;
    user: User;
  };
}
export type AuthStatus = 'authorized' | 'unauthorized' | 'pending';

const storeApi: StateCreator<AuthState> = (set) => ({
  status: 'unauthorized',
  token: undefined,
  user: undefined,

  loginUser: async (email: string, password: string, navigate: NavigateFunction) => {
    try {
      message.loading('登录中...', 0);
      await login({
        username: email,
        password: encrypt(password),
      }).then((res: any) => {
        console.log(res, 'kkkkkkkkkkkkk');

        const { token, ...user } = res;
        set({ status: 'authorized', token, user });
        message.destroy(); // 销毁消息
        message.success('登录成功！');

        navigate('/dashboard/dashboards'); // 登录成功后导航到指定页面
        return
        if (res.code === 200) {
          const { token, ...user } = res.data;
          set({ status: 'authorized', token, user });
          message.destroy(); // 销毁消息
          message.success('登录成功！');
        } else {
          set({ status: 'unauthorized', token: undefined, user: undefined });
          message.destroy(); // 销毁消息
          message.error('登录失败！');
          throw new Error("Invalid credentials"); // 你可以根据实际情况设置错误信息
        }
      })
    } catch (error) {
      console.error("Login error:", error);
      message.destroy(); // 销毁消息
      message.error('登录失败！');
      // 处理登录失败，例如显示错误消息
      set({ status: 'unauthorized', token: undefined, user: undefined });
      throw error; // 你也可以选择抛出错误供组件处理
    }
    finally {

    }
  },
});

export const useAuthStore = create<AuthState>()(
  devtools(
    persist(
      storeApi,
      { name: 'user-store' }
    )
  )
);
